from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.image import ImageModelSerializer, SKUSimpleModelSerializer
from apps.meiduo_admin.utils import PageNum
from fdfs_client.client import Fdfs_client


class ImageModelViewSet(ModelViewSet):
    queryset = SKUImage.objects.all()
    serializer_class = ImageModelSerializer
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        sku_id = request.data.get('sku')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response({'msg': '没有此商品'})

        client = Fdfs_client('meiduo_mail/utils/fastdfs/client.conf')
        image = request.FILES.get('image')
        result = client.upload_by_buffer(image.read())
        """
        {
            'Group name': 'group1', 
            'Remote file_id': 'group1/M00/00/02/wKizgF73cmqADnxDAACUZ3qFYbI3781188', 
            'Status': 'Upload successed.', 
            'Local file name': '', 
            'Uploaded size': '37.00KB', 
            'Storage IP': '192.168.179.128'
        }
        """
        if result['Status'] != 'Upload successed.':
            return Response({'msg': '上传失败'}, status=400)
        file_id = result.get('Remote file_id')
        new_sku_image = SKUImage.objects.create(
            sku=sku,
            image=file_id
        )
        return Response({
            "id": new_sku_image.id,
            "sku": sku_id,
            "image": new_sku_image.image.url
        }, status=201)


    def update(self, request, *args, **kwargs):
        sku_id = request.data.get('sku')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return Response({'msg': '没有此商品'})

        old_sku_image = self.get_object()
        image = request.FILES.get('image')
        client = Fdfs_client('meiduo_mail/utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image.read())
        if result['Status'] != 'Upload successed.':
            return Response({'msg': '上传失败'}, status=400)
        file_id = result['Remote file_id']
        old_sku_image.sku = sku
        old_sku_image.image = file_id
        old_sku_image.save()
        return Response({
            "id": old_sku_image.id,
            "sku": sku_id,
            "image": old_sku_image.image.url
        })


    def destroy(self, request, *args, **kwargs):
        old_sku_image = self.get_object()
        file_id = old_sku_image.image.name
        client = Fdfs_client('meiduo_mail/utils/fastdfs/client.conf')
        client.delete_file(file_id)
        old_sku_image.delete()
        return Response(status=204)

class SKUListAPIView(ListAPIView):
    queryset = SKU.objects.all()
    serializer_class = SKUSimpleModelSerializer




